const mysql = require('mysql2/promise')
const {env} = require('../config')
const { DbError } = require('../error')
// const { logger } = require('../utils/log');
// const { awaits } = require('../utils/O')


module.exports.env = env
const pool  = mysql.createPool({
  connectionLimit: env.MYSQL.LIMIT || 10,
  host: env.MYSQL.HOST,
  user: env.MYSQL.USER,
  password: env.MYSQL.PASS,
  database: env.MYSQL.DB,
  // ssl: {
  //   ca: fs.readFileSync(__dirname + '/mysql-ca.crt')
  //   rejectUnauthorized: false
  // }
  //  // disable FOUND_ROWS flag, enable IGNORE_SPACE flag
  // flags: '-FOUND_ROWS,IGNORE_SPACE'
})
const poolSlave  = mysql.createPool({
  connectionLimit: env.MYSQL_SLAVE.LIMIT || 10,
  host: env.MYSQL_SLAVE.HOST,
  user: env.MYSQL_SLAVE.USER,
  password: env.MYSQL_SLAVE.PASS,
  database: env.MYSQL_SLAVE.DB,
})

// 进程退出时自动关闭连接池
// process.on('exit', (code) => {
//   console.log('==== close mysql pool', code);
//   Promise.all(pool.end(), poolSlave.end())
//   .then(()=>{
//     console.log('==== mysql pool exited');
//   })
//   .catch(err => {
//     console.log('==== mysql pool exit fail', err);
//     logger.error({
//       code: err.code,
//       msg: err.message,
//       stack: err.stack
//     });
//   })
// })

pool.on('acquire', function (conn) {
  console.log('conn %d acquired', conn.threadId);
});
pool.on('connection', function (conn) {
  console.log('conn %d connected', conn.threadId);
  // conn.query('SET SESSION auto_increment_increment=1')
});
pool.on('release', function (conn) {
  console.log('conn %d released', conn.threadId);
});
pool.on('enqueue', function (conn) {
  console.log('conn %d enqueue', conn.threadId);
});
// 抽离成公共方法
const multi = { multipleStatements: true }


// 1.Error {
//  errno: -4078,
//  code: 'ECONNREFUSED',
//  syscall: 'connect',
//  address: '127.0.0.1',
//  port: 3306,
//  fatal: true
// }
exports.getConn = async (trans=false) => {
  const conn = await pool.getConnection()
  // let err
  // [err,conn] = await awaits(pool.getConnection())
  //   Error{name,message,stack,errno,code,syscall,address,port,fatal} null
  //   null Mysql.PoolConnection
  //   console.log('getconn ',typeof err ,'==', conn)
  if(trans)  await conn.beginTransaction()
  // 后面请自行调用
  // conn.rollback()
  // conn.commit()
  return conn
}

exports.getConns = async (trans=false) => {
  let conn
  try {
    conn = await pool.getConnection(multi)
    if(trans)  await conn.beginTransaction()
  }catch(e){
    if (e.errno) {
      throw new DbError(e.code, e.errno)
    } else {
      throw e
    }
  }
  return conn
}

exports.getConnSlave = async (trans=false) => {
  let conn
  try{
    conn = await poolSlave.getConnection()
    if(trans)  await conn.beginTransaction()
  }catch (e) {
    if (e.errno) {
      throw new DbError(e.code, e.errno)
    } else {
      throw e
    }
  }
  return conn
}

exports.getConnsSlave = async (trans=false) => {
  let conn
  try{
    conn = await poolSlave.getConnection(multi)
    if(trans)  await conn.beginTransaction()
  } catch (e) {
    if (e.errno) {
      throw new DbError(e.code, e.errno)
    } else {
      throw e
    }
  }
  return conn
}

// 2.Error {
//  code: 'ER_PARSE_ERROR',
//  errno: 1064,
//  sql: 'select * from  where id=? limit 1',
//  sqlState: '42000',
//  sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where id=? limit 1' at line 1"
// }
// exports.exec = (sql, values) => {
//   console.log("db pool");
//   return pool.execute(sql, values);
//   // pool.getConnection(function (err, connection) {
//   //   if (err) throw err;
//   //   console.log("get connection ");
//   //   //Use the connection
//   //   connection.query(sql, values, function (err, results, fields) {
//   //     console.log(err,JSON.stringify(results));
//   //     //每次查询都会 回调
//   //     callback(err, results);
//   //     //只是释放链接，在缓冲池了，没有被销毁
//   //     connection.release();
//   //     if (err) throw err;// new DbError(err.code,err.message);
//   //   });
//   // });
// }

// exports.execSlave = (sql, values, callback) => {
//   console.log("db pool");
//   poolSlave.getConnection(function (err, connection) {
//     if (err) throw err;
//     console.log("get slave connection ");
//     //Use the connection
//     connection.query(sql, values, function (err, results, fields) {
//       console.log(err, JSON.stringify(results));
//       //每次查询都会 回调
//       callback(err, results);
//       //只是释放链接，在缓冲池了，没有被销毁
//       connection.release();
//       if (err) throw err;
//     });
//   });
// }

